import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'
// 导入组件
// 同步导入组件
// import Login from '@/views/Login'
// 按需加载组件
// const Login  = () => import('@/views/Login')
// ctrl + 右箭头   fn + 右箭头
const Login = () => import('@/views/Login')
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/Layout/Home')
const QA = () => import('@/views/Layout/QA')
const Video = () => import('@/views/Layout/Video')
const User = () => import('@/views/Layout/User')
const UserEdit = () => import('@/views/Layout/User/edit')
const UserChat = () => import('@/views/Layout/User/chat')
const NotFound = () => import('@/views/NotFound')
const Search = () => import('@/views/Search')
const SearchResult = () => import('@/views/Search/result')
const Article = () => import('@/views/Article')
Vue.use(VueRouter)

// 1. 把 VueRouter原型上的push备份
const originalPush = VueRouter.prototype.push
// 2. 替换了原来的push方法，并且统一的提供了catch
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: Home,
        // 路由的元信息，可以在这个meta中提供任意的数据
        meta: {
          isKeepAlive: true
        }
      },
      {
        path: '/qa',
        component: QA
      },
      {
        path: '/video',
        component: Video
      },
      {
        path: '/user',
        component: User
      }
    ]
  },
  {
    path: '/user/edit',
    component: UserEdit
  },
  {
    path: '/user/chat',
    component: UserChat
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: SearchResult
  },
  {
    // 动态的路由参数
    // /article/:id 能够匹配到 /article/xxx 所有的路由
    path: '/article',
    component: Article
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

/*
  1. 判断用户是否有token
  2. 如果有token，放行
  3. 如果没有token
  4. 判断to.path是否在白名单中
  5. 如果是，放行
  6. 如果不是，跳转到登录页
*/
const whiteList = ['/login', '/', '/qa', '/video', '/404', '/search', '/search/result', '/article']
router.beforeEach(function (to, from, next) {
  const token = store.state.token.token
  if (token) {
    // 有token, 先发送请求-把数据存储到vuex中
    // 1. 判断vuex中有没有user数据
    // 2. 如果vuex中没有user数据，发送请求-保存到vuex中，，，，保证任何组件都能通过vuex获取数据
    if (!store.state.user.name) {
      // vuex中没有user数据
      store.dispatch('getUser')
    }
    return next()
  }
  // 没有token
  if (whiteList.includes(to.path)) {
    return next()
  }
  // if (to.path.startsWith('/article')) {
  //   return next()
  // }
  // 没有登录，也不在白名单
  // path: 路径  query: 额外的参数
  next({ path: '/login', query: { back: to.path } })
})

export default router
